<?php

class memoryCache {

    private $memcache_Instance = null;

    function __construct() {
        $this->memcache_Instance = new Redis();
        $this->memcache_Instance->connect(CACHE_REDIS_ADDR, CACHE_REDIS_PORT);
    }

    public function set($key, &$value, $timeout) {
        $newKey = REDIS_PREFIX . $key;                  //ʹ�ñ�����ǰ׺
        $tmp = array('SC_TIMESTAMP' => time(), 'SC_TIMEOUT' => $timeout, 'SC_VALUE' => $value);
        if ($timeout == 0) {
            return $this->memcache_Instance->set($newKey, json_encode($tmp));
        } else {
            return $this->memcache_Instance->setex($newKey, $timeout, json_encode($tmp));
        }
    }

    public function get($key) {
        $newKey = REDIS_PREFIX . $key;                  //ʹ�ñ�����ǰ׺
        if ($tmp = json_decode($this->memcache_Instance->get($newKey), true)) {
            $sc_timestamp = $tmp['SC_TIMESTAMP'];
            $sc_timeout = $tmp['SC_TIMEOUT'];
            if (($sc_timeout == -1 || $sc_timeout == 0) || ($sc_timeout > 0 && time() - $sc_timestamp <= $sc_timeout))
                return $tmp['SC_VALUE'];
            else {  // time out
                $this->memcache_Instance->delete($newKey);
                return null;
            }
        }else
            return null;
    }

    public function remove($key) {
        $newKey = REDIS_PREFIX . $key;                  //ʹ�ñ�����ǰ׺
        return $this->memcache_Instance->delete($newKey);
    }

    public function cleanup() {
        $this->memcache_Instance->flushDB();
    }

    public function getStats($name) {
        return $this->memcache_Instance->getOption($name);
    }

    public function zAdd($key,$score,$member) {
        $newKey = REDIS_PREFIX . $key;                  //ʹ�ñ�����ǰ׺
        return $this->memcache_Instance->zAdd($newKey,$score,$member);
    }

    public function zRange( $key, $start, $end, $withscores = null ){
        $newKey = REDIS_PREFIX . $key;                  //ʹ�ñ�����ǰ׺
        return $this->memcache_Instance->zRange( $newKey, $start, $end, $withscores );
    }

    public function keys($pattern) {
        return $this->memcache_Instance->keys($pattern);
    }
}